package com.cm.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cm.common.core.Result;
import com.cm.common.entity.User;
import com.cm.user.core.Token;
import com.cm.user.mapper.UserMapper;
import com.cm.user.service.UserService;
import com.cm.user.utils.JwtUtils;
import com.google.j2objc.annotations.AutoreleasePool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.cm.user.constrant.GlobalConstrant.TOKEN_PASSWORD;

/**
 * @类 名：IndexController </br>
 * @描 述：</br>
 * @日 期：2020/9/24 17:10</br>
 * @作 者：刘海龙</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/user")
public class IndexController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    public Result login(String account, String password) {
        if (userService.login(account, password)) {
            Token token = new Token();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("account", account);
            User user = userMapper.selectOne(queryWrapper);
            token.setToken(JwtUtils.sign(user.getId(), account, TOKEN_PASSWORD));
            return Result.success(token, "用户登录成功");

        } else {
            return Result.fail("用户登录失败");
        }
    }
    @PostMapping("/getId")
    public Long getUserId(String token){
        return JwtUtils.getId(token);
    }

}
